package com.rc.saas.mini.controller.enterprise;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.mq.MqConfig;
import com.rc.saas.mini.common.mq.MqProducer;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.enterprise.*;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.rc.RcMsgNotification;
import com.rc.saas.mini.service.enterprise.EnterpriseMemberApplyService;
import com.rc.saas.mini.service.enterprise.EnterpriseMemberService;
import com.rc.saas.mini.service.enterprise.EnterpriseSubmemberApplyService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.rc.RcMsgNotificationService;
import com.rc.saas.mini.vo.base.RcPageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description
 * @Author
 * @Date: 2022-06-01
 */

@Api(tags = "21.企业申请")
@Controller
@RequestMapping("/enterpriseMemberApply")
public class EnterpriseMemberApplyController extends MinipBaseController {

    private static Logger logger = LogManager.getLogger(EnterpriseMemberApplyController.class);

    @Autowired
    private EnterpriseMemberApplyService enterpriseMemberApplyService;

    @Autowired
    private EnterpriseSubmemberApplyService enterpriseSubmemberApplyService;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private RcMsgNotificationService rcMsgNotificationService;

    @Autowired
    private MemberInfoService memberInfoService;


    @Autowired
    private MqProducer mqProducer;

    /**
     * 增
     */
    @ApiOperation(value = "企业申请(认证)", httpMethod = "POST")
    @RequestMapping(value = "/saveEnterpriseMemberApply", method = RequestMethod.POST)
    @ResponseBody
    private DataTResponse saveOrUpdateEnterpriseMemberApply(HttpServletRequest request, EnterpriseMemberApply enterpriseMemberApply) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null || loginInfo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }

        EnterpriseSubmemberApplyExample example = new EnterpriseSubmemberApplyExample();
        example.createCriteria().andMemberIdEqualTo(loginInfo.getMemberId());
        example.setOrderByClause("last_updated_time desc,created_time desc");

        //判断是否重复申请
        List<EnterpriseSubmemberApply> oldList = enterpriseSubmemberApplyService.selectByExample(example);
        if (!CollectionUtils.isEmpty(oldList) && oldList.stream()
                .filter(data -> "0".equals(data.getStatus()) || "1".equals(data.getStatus())).findFirst().orElseGet(() -> null) != null) {
            return DataTResponse.FAIL("用户已申请!");
        }
        //判断是否已经企业认证
        EnterpriseMember enterpriseMember = enterpriseMemberService.selectByMemberId(loginInfo.getMemberId());
        if(!Objects.isNull(enterpriseMember) && "0".equals(enterpriseMember.getStatus())){
            return DataTResponse.FAIL("该用户已认证!");
        }

        enterpriseMemberApply.setTenantCode(loginInfo.getTenantCode());
        enterpriseMemberApply.setMemberId(loginInfo.getMemberId());
        enterpriseMemberApply.setStatus("0");
        enterpriseMemberApply.setApplyType("0");
        enterpriseMemberApply.setEnterpriseApplyId(null);
        enterpriseMemberApply.setCreatedTime(new Date());
        enterpriseMemberApply.setCreatedBy(loginInfo.getMemberId() + "");
        //核对是否有同名企业
        EnterpriseMemberApplyExample enterpriseMemberApplyExample = new EnterpriseMemberApplyExample();
        enterpriseMemberApplyExample.createCriteria().andEnterpriseNameEqualTo(enterpriseMemberApply.getEnterpriseName());
        enterpriseMemberApplyExample.setOrderByClause("created_time desc");
        EnterpriseMemberApply enterpriseMemberApply1 = enterpriseMemberApplyService.selectByExample(enterpriseMemberApplyExample).stream().findFirst().orElseGet(() -> null);
        //
        if ((enterpriseMemberApply1 != null && "2".equals(enterpriseMemberApply1.getStatus())) || enterpriseMemberApply1 == null) {
            //存在同名且审核不通过或者不存在，重新申请
            enterpriseMemberApplyService.insertByReturnId(enterpriseMemberApply);
        } else if (enterpriseMemberApply1 != null) {
            //绑定其下申请
            enterpriseMemberApply.setEnterpriseId(enterpriseMemberApply1.getEnterpriseId());
        }

        EnterpriseSubmemberApply enterpriseSubmemberApply = new EnterpriseSubmemberApply();
        BeanUtils.copyProperties(enterpriseMemberApply, enterpriseSubmemberApply);
        MemberInfo memberInfo=memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());

        enterpriseSubmemberApply.setMemberId(memberInfo.getMemberId());
        enterpriseSubmemberApply.setNickname(memberInfo.getNickname());
        enterpriseSubmemberApply.setPhone(memberInfo.getMobile());
        enterpriseSubmemberApply.setRecommenderId(memberInfo.getRecommenderId());
        enterpriseSubmemberApply.setBirthday(memberInfo.getBirthday());
        enterpriseSubmemberApply.setSex(memberInfo.getSex());
        enterpriseSubmemberApply.setNameWx(memberInfo.getNameWx());
        //enterpriseSubmemberApplyService.insertSelective(enterpriseSubmemberApply);
        enterpriseSubmemberApplyService.insertByReturnId(enterpriseSubmemberApply);


        HashMap<String, Long> map = new HashMap<>();
        map.put("enterpriseApplyId", enterpriseSubmemberApply.getSubmemberApplyId());
        // 发送mq 给后台
        mqProducer.send(MqConfig.platform_apply, JSON.toJSONString(map));
        RcMsgNotification rcMsgNotification = new RcMsgNotification();
        rcMsgNotification.setTenantCode(loginInfo.getTenantCode());
        rcMsgNotification.setMsgType("0");
        rcMsgNotification.setMsgId(enterpriseSubmemberApply.getSubmemberApplyId().toString());
        rcMsgNotificationService.saveRcMsgNotification(rcMsgNotification);

        return DataTResponse.SUCCESS();
    }


    /**
     * 查询
     */
    @ApiOperation(value = "查询单个 企业申请记录", httpMethod = "POST")
    @RequestMapping(value = "/selectByEnterpriseApplyId", method = RequestMethod.POST)
    @ResponseBody
    private DataTResponse<EnterpriseMemberApply> selectByEnterpriseApplyId(HttpServletRequest request, Long enterpriseApplyId) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null || loginInfo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        EnterpriseMemberApply enterpriseMemberApply = new EnterpriseMemberApply();
        enterpriseMemberApply.setMemberId(loginInfo.getMemberId());
        enterpriseMemberApply.setEnterpriseApplyId(enterpriseApplyId);
        List<EnterpriseMemberApply> list = enterpriseMemberApplyService.listByCondition(enterpriseMemberApply);

        return DataTResponse.SUCCESS_DATA(list.stream().findFirst().orElseGet(() -> null));
    }


    /**
     * 查询列表分页
     */
    @ApiOperation("查询列表分页 企业申请记录")
    @RequestMapping(value = "/listPageByEnterpriseMemberApply", method = RequestMethod.POST)
    @ResponseBody
    private DataTResponse<PageInfo<EnterpriseMemberApply>> listPageByEnterpriseMemberApply(HttpServletRequest request, EnterpriseMemberApply enterpriseMemberApply, RcPageVo lkPageVo) {
        //Page
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null || loginInfo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        enterpriseMemberApply.setMemberId(loginInfo.getMemberId());
        PageHelper.startPage(lkPageVo.getPageNo(), lkPageVo.getPageSize());
        List<EnterpriseMemberApply> list = enterpriseMemberApplyService.listByCondition(enterpriseMemberApply);
        PageInfo<EnterpriseMemberApply> pageInfo = new PageInfo<>(list);
        return DataTResponse.SUCCESS_DATA(pageInfo);
    }


}
